package com.eagle.rate.service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eagle.rate.common.util.DateUtil;
import com.eagle.rate.dao.RateDAO;
import com.eagle.rate.dao.UserDAO;
import com.eagle.rate.entity.Rate;
import com.eagle.rate.entity.User;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.ArticleUserSubscribe;
import com.taobao.api.domain.Trade;
import com.taobao.api.domain.TradeRate;
import com.taobao.api.request.TradeFullinfoGetRequest;
import com.taobao.api.request.TraderatesGetRequest;
import com.taobao.api.request.VasSubscribeGetRequest;
import com.taobao.api.response.TradeFullinfoGetResponse;
import com.taobao.api.response.TraderatesGetResponse;
import com.taobao.api.response.VasSubscribeGetResponse;

@Service("TaobaoRateService")
public class TaobaoRateService {

	@Autowired
	private RateDAO rateDAO;
	@Autowired
	private UserDAO userDAO;
	private static final Log _log = LogFactory.getLog(TaobaoRateService.class);
	private static final String TAOBAOURL = "http://gw.api.taobao.com/router/rest";
	// private static final String APPKEY = "12647603";
	// private static final String APPSECRET =
	// "f2493ee76a1c2dff98e4c4e7006d5c99";

	// flower
	private static final String APPKEY = "12181096";
	private static final String APPSECRET = "98a05f4911b21d3a592f02a812b3beef";

	public void test() {
		List<User> listUser = userDAO.findNotDownload(DateUtil
				.getStringyyyy_MM_dd_HH_mm_ss());
		_log.debug("listUser.size()===================" + listUser.size());
	}

	/**
	 * 
	 * 根据传入的信息检查是否有权限访问内部应用
	 * 1.查找数据库是否存在该用户信息，如果不存在就到2，如果存在就判断是否过期，如果过期就到2，如果没过期就返回继续正常访问的信息
	 * 2.去top获取该用户的订购信息
	 * ，如果不存在就到3，如果存在就判断是否过期，如果没有过期就把信息更新或者新增到数据库，如果过期了就返回订购过期的信息 3.返回 未订购的信息
	 * 
	 * @param nick
	 * @return 1.正常访问 2.没有订购 3.订购过期
	 * @throws ApiException
	 */
	public int checkNick(String nick, String topSession) throws ApiException {
		return 1;   //这是测试
//		// 查找数据库是否存在该用户信息
//		List<User> list_ = userDAO.findByUserName(nick);
//		boolean has_data = false;
//		if (list_.size() != 0) {
//			has_data = true;
//			// 找出dealline
//			if (!DateUtil.isDateBefore(DateUtil.timestampToString(list_.get(0)
//					.getDeadline()))) {
//				return 1;
//			}
//		}
//
//		// 如果数据库不存在信息或者已经过期就到top获取用户的最新订购信息，再次验证是否真的有订购和是否订购是否真的过期。
//		TaobaoClient client = new DefaultTaobaoClient(this.TAOBAOURL,
//				this.APPKEY, this.APPSECRET);
//		VasSubscribeGetRequest req = new VasSubscribeGetRequest();
//		req.setNick(nick);
//		req.setArticleCode("ts-30988-1");
//		VasSubscribeGetResponse response = client.execute(req);
//		if (response.isSuccess()) {
//			List<ArticleUserSubscribe> list = response
//					.getArticleUserSubscribes();
//			if (list.size() == 0) {
//				return 2;// 2.没有订购 
//			} else {
//				for (int i = 0; i <= list.size(); i++) {
//					ArticleUserSubscribe articleUserSubscribe = list.get(i);
//					articleUserSubscribe.getDeadline();
//					if (!DateUtil.isDateBefore(DateUtil
//							.formatyyyy_MM_dd_HH_mm_ss(articleUserSubscribe
//									.getDeadline()))) {//订购未过期
//						// 检测数据库是否存在该信息
//						if (has_data) {
//							// 更新
//							User user = list_.get(0);
//							user.setDeadline(DateUtil
//									.DateToTimestamp(articleUserSubscribe
//											.getDeadline()));
//							userDAO.save(user);
//						} else {
//							// 插入
//							User newUser = new User(
//									nick,
//									topSession,
//									null,
//									null,
//									DateUtil.DateToTimestamp(articleUserSubscribe
//											.getDeadline()));
//							userDAO.save(newUser);
//						}
//						return 1;
//					} else {//订购过期
//						return 3;
//					}
//				}
//			}
//		}
//		return 1;
	}

	public void downRateJob() {
		// 找出当天未更新的用户ID，包括null的
		List<User> listUser = userDAO.findNotDownload(DateUtil
				.getStringyyyy_MM_dd());
		if (listUser.size() > 0) {
			Iterator<User> iteatorUser = listUser.iterator();
			while (iteatorUser.hasNext()) {
				User user = iteatorUser.next();
				Map<String, String> keys = new HashMap<String, String>();
				keys.put("appkey", APPKEY);
				keys.put("secret", APPSECRET);
				keys.put("session", user.getSessionkey());
				int userId = user.getId();
				if (user.getDownloadDate() == null) {
					// 如果为null，为初始下载，下载前10天
					String endDate = DateUtil.getStringyyyy_MM_dd_HH_mm_ss();
					String startDate = DateUtil
							.formatyyyy_MM_dd_HH_mm_ss(DateUtil.getAddDays(-10));
					try {
						this.downRateCore(userId, keys, "bad", startDate,
								endDate);
						this.downRateCore(userId, keys, "neutral", startDate,
								endDate);
						user.setDownloadDate(new Timestamp(DateUtil
								.parseyyyy_MM_dd_HH_mm_ss(endDate).getTime()));
						// 记录下载时间
						userDAO.save(user);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						_log.error(e);
						try {
							Thread.sleep(5000);// 如果出现异常。暂停5秒再执行。
						} catch (InterruptedException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
				} else {
					String startDate = DateUtil.formatyyyy_MM_dd_HH_mm_ss(user
							.getDownloadDate());
					String endDate = DateUtil.getStringyyyy_MM_dd_HH_mm_ss();
					try {
						this.downRateCore(userId, keys, "bad", startDate,
								endDate);
						this.downRateCore(userId, keys, "neutral", startDate,
								endDate);

						user.setDownloadDate(new Timestamp(DateUtil
								.parseyyyy_MM_dd_HH_mm_ss(endDate).getTime()));
						userDAO.save(user);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						_log.error(e);
						try {
							Thread.sleep(5000);
						} catch (InterruptedException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
				}
			}
		}
	}

	/**
	 * 
	 * @param userId
	 * @param startDate_
	 * @param endDate
	 * @throws Exception
	 *             用户自定义下载
	 */
	public void downRateCustom(int userId, String startDate, String endDate)
			throws Exception {
		// 找出keys
		User user = userDAO.findById(userId);
		if (user == null) {
			Exception e = new Exception("用户ID不存在");
			throw e;
		}
		Map<String, String> keys = new HashMap<String, String>();
		keys.put("appkey", APPKEY);
		keys.put("secret", APPSECRET);
		keys.put("session", user.getSessionkey());

		downRateCore(userId, keys, "bad", startDate, endDate);
		downRateCore(userId, keys, "neutral", startDate, endDate);
	}

	/**
	 * 
	 * @param user_id
	 *            卖家ID
	 * @param keys
	 *            topkey
	 * @param result
	 *            评价结果
	 * @param startDate_
	 *            开始时间
	 * @param endDate_
	 *            结束时间
	 * @throws Exception
	 * @todo 下载核心方法
	 */
	private void downRateCore(int userId, Map<String, String> keys,
			String result, String startDate_, String endDate_) throws Exception {
		try {
			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyy-MM-dd hh:mm:ss");
			String appkey = keys.get("appkey");
			String secret = keys.get("secret");
			String session = keys.get("session");
			Date startDate;
			startDate = formatter.parse(startDate_);
			Date endDate;
			endDate = formatter.parse(endDate_);
			long page = 1;
			long pageSize = 50;
			boolean hasNext = true;
			TaobaoClient client = new DefaultTaobaoClient(TAOBAOURL, appkey,
					secret);
			TraderatesGetRequest req = new TraderatesGetRequest();
			req.setFields("tid,oid,role,rated_nick,nick,result,created,item_title,item_price,content,reply");
			req.setRateType("get");
			req.setRole("buyer");
			req.setPageSize(pageSize);
			req.setStartDate(startDate);
			req.setEndDate(endDate);
			req.setResult(result);
			req.setUseHasNext(true);
			TraderatesGetResponse traderatesGetRes;

			while (hasNext) {
				req.setPageNo(page++);
				traderatesGetRes = client.execute(req, session);
				hasNext = traderatesGetRes.getHasNext();
				_log.debug(traderatesGetRes.getTotalResults());
				if (traderatesGetRes.isSuccess()) {
					_log.debug(traderatesGetRes.getBody().toString());
					List<TradeRate> tradeRates_ = traderatesGetRes
							.getTradeRates();
					if (tradeRates_ == null) {
						return;
					}
					Iterator<TradeRate> itr = tradeRates_.iterator();
					while (itr.hasNext()) {
						TradeRate tradeRate = itr.next();
						Rate taobaoRate = new Rate();
						taobaoRate.setItemTitle(tradeRate.getItemTitle());// title
						taobaoRate.setNick(tradeRate.getNick()); // nick
						taobaoRate.setContent(tradeRate.getContent()); // content
						taobaoRate.setItemPrice(Double.valueOf(tradeRate
								.getItemPrice()));// price
						taobaoRate.setCreated(Timestamp.valueOf(formatter
								.format(tradeRate.getCreated())));// created
						taobaoRate.setTid(tradeRate.getTid().toString());// tid
						taobaoRate.setOid(tradeRate.getOid().toString());// oid
						taobaoRate.setResult(tradeRate.getResult());// result
						List<Rate> existlist = rateDAO.findByOid(tradeRate
								.getOid().toString());
						if (!existlist.isEmpty()) {
							continue;
						}

						TradeFullinfoGetRequest tradeFullinfoReq = new TradeFullinfoGetRequest();
						tradeFullinfoReq.setTid(Long.parseLong(String
								.valueOf(tradeRate.getTid())));
						tradeFullinfoReq
								.setFields("receiver_name,receiver_mobile");
						TradeFullinfoGetResponse tradeFullinfoGetRes = client
								.execute(tradeFullinfoReq, session);
						if (tradeFullinfoGetRes.isSuccess()) {
							Trade trade = tradeFullinfoGetRes.getTrade();
							_log.debug("receiver_name:"
									+ trade.getReceiverName());

							taobaoRate.setSellerName(trade.getReceiverName());
							taobaoRate.setSellerMobile(trade
									.getReceiverMobile());
							_log.debug("receiver_mobile:"
									+ trade.getReceiverMobile());
							taobaoRate.setUserId(userId);
							rateDAO.save(taobaoRate);
						} else {
							throw new Exception(traderatesGetRes.getErrorCode()
									+ ":" + traderatesGetRes.getMsg());
						}
					}
				} else {
					throw new Exception(traderatesGetRes.getErrorCode() + ":"
							+ traderatesGetRes.getMsg());
				}
			}
		} catch (Exception e) {
			throw e;
		}
	}

	private void updateRateCore(Map<String, String> keys, String tid) {

	}

	public List<Rate> findNotModity() throws Exception {
		// 计算前20天的时间
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd hh:mm:ss");
		Date currDate = new Date();
		Date startDate = DateUtil.getAddDays(currDate, -20);
		String date = simpleDateFormat.format(startDate);
		String hsql = " from Rate where   created>='" + date + "' ";
		return null;
	}

}